﻿namespace HuwmanCode.ServiceProcess

open System
open System.Diagnostics
open System.ComponentModel
open System.Configuration
open System.Configuration.Install
open System.ServiceProcess

[<RunInstaller(true)>]
type public ServiceProjectInstallerBase() as this =
    inherit Installer()
    do
        let processInstaller = new ServiceProcessInstaller()    
        let serviceAccount = this.GetType().GetCustomAttributes(typeof<ServiceAccountAttribute>, false)
                             |> Array.map(fun e -> e :?> ServiceAccountAttribute) |> Array.tryFind(fun e -> true)

        match serviceAccount with
        | None -> processInstaller.Account <- ServiceAccount.LocalService
        | Some(account) ->
                processInstaller.Account <- account.Account
                processInstaller.Username <- account.UserName

        let installers =  (processInstaller :> Installer) :: Base.GetServiceInstallers()
        base.Installers.AddRange(installers |> List.toArray)
    
    override x.Commit(savedState) =
        let servicesToStart = Base.Services |> Array.filter(fun s -> s.StartAfterInstall)
        for service in servicesToStart do
            use sc = new ServiceController(service.ServiceName)
            try
                if sc.Status = ServiceControllerStatus.Stopped then
                    sc.Start()
            with
            | :? Win32Exception -> ignore service
            | :? InvalidOperationException -> ignore service
                
